package com.jy.adscm.order.service.impl;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jy.adscm.bean.system.JyCode;
import com.jy.adscm.bean.system.JyUser;
import com.jy.adscm.dealer.bean.Dealer;
import com.jy.adscm.dealer.mapper.DealerMapper;
import com.jy.adscm.exception.AdscmSystemException;
import com.jy.adscm.order.bean.JyOrder;
import com.jy.adscm.order.bean.JyProduct;
import com.jy.adscm.order.mapper.JyOrderMapper;
import com.jy.adscm.order.mapper.JyProductMapper;
import com.jy.adscm.order.service.JyOrderService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jy.adscm.security.utils.Token;
import com.jy.adscm.stock.bean.JyInStorage;
import com.jy.adscm.stock.mapper.JyInStorageMapper;
import com.jy.adscm.system.mapper.mysql.JyCodeMapper;
import com.jy.adscm.system.mapper.mysql.JyUserMapper;
import com.jy.adscm.utils.AdscmBaseUtils;
import com.jy.adscm.utils.AdscmDateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zyl
 * @since 2019-01-18
 */
@Service
public class JyOrderServiceImpl extends ServiceImpl<JyOrderMapper, JyOrder> implements JyOrderService {
     @Autowired
    JyUserMapper jyUserMapper;
     @Autowired
    DealerMapper dealerMapper;
     @Autowired
    JyCodeMapper jyCodeMapper;
     @Autowired
     JyProductMapper jyProductMapper;
     @Autowired
    JyInStorageMapper jyInStorageMapper;
     @Transactional
    @Override
    public boolean insertJyOrder(JyOrder jyOrder, Token token) throws AdscmSystemException {
        jyOrder.setCreateTime(new Date());
        jyOrder.setCreator(token.getUser().getId().toString());
        jyOrder.setOrderState(0);
        jyOrder.setDealer(token.getUser().getUnitId().toString());
        //查询这个月最大的订单号
        Wrapper<JyOrder> wrapper =new EntityWrapper<>();
        wrapper.like("order_num",new SimpleDateFormat("yyyyMMdd").format(new Date()), SqlLike.RIGHT);
        wrapper.orderBy("order_num",false);
        List<JyOrder> jyOrders = super.selectList(wrapper);
        if(jyOrders.size()>0){
            JyOrder oldjyOrder = jyOrders.get(0);
            String orderNum = oldjyOrder.getOrderNum();
           long result=  Long.valueOf(orderNum.trim()) +1;

            jyOrder.setOrderNum(String.valueOf(result));
        }else {
            jyOrder.setOrderNum(new SimpleDateFormat("yyyyMMdd").format(new Date())+"0000");
        }
        boolean insert = super.insert(jyOrder);
        return insert;
    }
    @Transactional
    @Override
    public boolean deleteJyOrder(Integer id, Token token) throws AdscmSystemException {
        JyOrder jyOrder = super.selectById(id);
        if(jyOrder.getOrderState()!=0){
            throw new AdscmSystemException("该记录不能删除");
        }
        boolean b = super.deleteById(id);
        return b;
    }
    @Transactional
    @Override
    public Boolean updateJyOrder(JyOrder jyOrder, Token token) throws AdscmSystemException {
        Boolean  result=false;
        //待审核
        if (jyOrder.getOrderState()==0){
            jyOrder.setApprover(token.getUser().getId().toString());
            jyOrder.setApproveTime(new Date());
            //审核通过
            if("1".equals(jyOrder.getApproveResult())){
                jyOrder.setOrderState(2);
             }
            if (jyOrder.getOrderState()==2 && AdscmBaseUtils.getInstance().isNotEmpty(jyOrder.getLogisticsCompany(),null)
                    &&  AdscmBaseUtils.getInstance().isNotEmpty(jyOrder.getLogisticsNum(),null)){
                jyOrder.setOutStorageTime(new Date());
                jyOrder.setOrderState(3);
            }
            result   = super.updateById(jyOrder);
            return result;
        }
        //待起运
        if (jyOrder.getOrderState()==2 && AdscmBaseUtils.getInstance().isNotEmpty(jyOrder.getLogisticsCompany(),null)
             &&  AdscmBaseUtils.getInstance().isNotEmpty(jyOrder.getLogisticsNum(),null)){
            jyOrder.setOutStorageTime(new Date());
            jyOrder.setOrderState(3);
            jyOrder.setLastSignTime(AdscmDateUtils.getThatDate(new Date(),30, Calendar.DATE));
            result   = super.updateById(jyOrder);
            return result;
        }
        //待签收
        if (jyOrder.getOrderState()==3 && AdscmBaseUtils.getInstance().isNotEmpty(jyOrder.getSignTime(),null)){
             if (token.getUser().getUnitId()==0){
                 throw  new AdscmSystemException("您不能签收该订单");
             }
             jyOrder.setSignPerson(token.getUser().getId().toString());
             jyOrder.setOrderState(1);
             //生成入库信息
            JyInStorage  jyInStorage =new JyInStorage();
            jyInStorage.setOrderNum(jyOrder.getOrderNum());
            jyInStorage.setUnit(jyOrder.getUnit());
            jyInStorage.setInstorageNum(jyOrder.getNum());
            jyInStorage.setInstorageTime(new Date());
            jyInStorage.setOrderTime(jyOrder.getCreateTime());
            jyInStorage.setProduct(jyOrder.getProduct());
            JyProduct jyProduct = jyProductMapper.selectById(jyOrder.getProduct());
            jyInStorage.setType(jyProduct.getType());
            jyInStorage.setTypeNum(jyProduct.getTypeNum());
            jyInStorage.setDealer(jyOrder.getDealer());
            Integer insert = jyInStorageMapper.insert(jyInStorage);
            result   = super.updateById(jyOrder);
            return result;
        }

        return result;
    }

    @Override
    public List<JyOrder> selectBystate(Integer state,Token token) throws AdscmSystemException {
        List<JyOrder> jyOrders = new ArrayList<>();
      
        if (token.getUser().getUnitId()==0){
            //厂家的用户
            if (state==0){
                //待办的
                Wrapper<JyOrder> wrapper =new EntityWrapper<>();
                wrapper.ne("order_state",1);
                jyOrders = super.selectList(wrapper);
               

            }else{
                //已办的
                Wrapper<JyOrder> wrapper =new EntityWrapper<>();
                wrapper.eq("order_state",1);
                jyOrders = super.selectList(wrapper);
            }

        }
         else {
             //经销商
            if (state==0){
                //待办的
                Wrapper<JyOrder> wrapper =new EntityWrapper<>();
                wrapper.eq("dealer",token.getUser().getUnitId().toString());
                wrapper.ne("order_state",1);
                jyOrders = super.selectList(wrapper);


            }else{
                //已办的
                Wrapper<JyOrder> wrapper =new EntityWrapper<>();
                wrapper.eq("dealer",token.getUser().getUnitId().toString());
                wrapper.eq("order_state",1);
                jyOrders = super.selectList(wrapper);
            }

        }

        for (JyOrder jyOrder : jyOrders) {
         if (AdscmBaseUtils.getInstance().isNotEmpty(jyOrder.getCreator(),null)){
            JyUser jyUser = jyUserMapper.selectById(jyOrder.getCreator());
            jyOrder.setCreatorName(jyUser.getName());
          }
          if (AdscmBaseUtils.getInstance().isNotEmpty(jyOrder.getApprover(),null)){
              JyUser jyUser = jyUserMapper.selectById(jyOrder.getApprover());
              jyOrder.setApproverName(jyUser.getName());
          }
          if (AdscmBaseUtils.getInstance().isNotEmpty(jyOrder.getSignPerson(),null)){
              JyUser jyUser = jyUserMapper.selectById(jyOrder.getSignPerson());
              System.err.println(jyOrder.getSignPerson());
              jyOrder.setSignPersonName(jyUser.getName());
          }
          if (AdscmBaseUtils.getInstance().isNotEmpty(jyOrder.getDealer(),null)){
              Dealer dealer = dealerMapper.selectById(jyOrder.getDealer());
              jyOrder.setDealerName(dealer.getName());
          }
          if (AdscmBaseUtils.getInstance().isNotEmpty(jyOrder.getProduct(),null)){
              JyProduct jyProduct = jyProductMapper.selectById(jyOrder.getProduct());
              jyOrder.setProductName(jyProduct.getName());
          }
          if (AdscmBaseUtils.getInstance().isNotEmpty(jyOrder.getOrderState(),null)){
              JyCode jyCode = new JyCode();
              jyCode.setCode(jyOrder.getOrderState().toString());
              jyCode.setType(5);
              jyCode = jyCodeMapper.selectOne(jyCode);
              jyOrder.setOrderStateName(jyCode.getName());
          }
          if (AdscmBaseUtils.getInstance().isNotEmpty(jyOrder.getUnit(),null)){
              JyCode jyCode = new JyCode();
              jyCode.setCode(jyOrder.getUnit());
              jyCode.setType(6);
              jyCode = jyCodeMapper.selectOne(jyCode);
              jyOrder.setUnitName(jyCode.getName());
          }
        }
        
        return jyOrders;
    }

    @Override
    public Boolean signOrder(Integer id, Token token) throws AdscmSystemException {

        JyOrder jyOrder = super.selectById(id);
        Boolean  result =false;
        if(token.getUser().getUnitId()==0){
            throw  new AdscmSystemException("您不能签收该订单");
        }
        if (jyOrder.getOrderState()==3){
            jyOrder.setSignPerson(token.getUser().getId().toString());
            jyOrder.setSignTime(new Date());
            jyOrder.setOrderState(1);
            //生成入库信息
            JyInStorage  jyInStorage =new JyInStorage();
            jyInStorage.setOrderNum(jyOrder.getOrderNum());
            jyInStorage.setUnit(jyOrder.getUnit());
            jyInStorage.setInstorageNum(jyOrder.getNum());
            jyInStorage.setInstorageTime(new Date());
            jyInStorage.setOrderTime(jyOrder.getCreateTime());
            jyInStorage.setProduct(jyOrder.getProduct());
            JyProduct jyProduct = jyProductMapper.selectById(jyOrder.getProduct());
            jyInStorage.setType(jyProduct.getType());
            jyInStorage.setTypeNum(jyProduct.getTypeNum());
            jyInStorage.setDealer(jyOrder.getDealer());
            Integer insert = jyInStorageMapper.insert(jyInStorage);
            result = super.updateById(jyOrder);
        }else {
            throw  new AdscmSystemException("不能签收");
        }
        return result;
    }
}
